//
//  MCChargeInViewController.m
//  ERP
//
//  Created by QA on 15/11/5.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MCChargeInViewController.h"

#import "UITableView+Custom.h"
#import "MJRefresh.h"
#import "MCChargeInViewCell.h"
#import "MCChargeInRowViewCell.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

#import "WebServiceCommonRequest.h"
#import "GEDateFromatter.h"

#import "MCSearchChargeInViewController.h"

@interface MCChargeInViewController ()<SKSTableViewDelegate>

@property (strong, nonatomic) NSMutableArray *resultData;
@property (assign, nonatomic) NSInteger segmentActionState;

@property (strong, nonatomic) NSString *searchStartTime;
@property (strong, nonatomic) NSString *searchEndTime;

@end

@implementation MCChargeInViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"原材进料统计分析"];
        
        //设置搜索按钮
        UIButton* righButtont= [UIButton buttonWithType:UIButtonTypeCustom];
        righButtont.frame = CGRectMake(0, 0, 44, 44);
        [righButtont setImage:[UIImage imageNamed:@"home_nav_left_serch"] forState:UIControlStateNormal];
        [righButtont addTarget:self action:@selector(searchChargeInSelector:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:righButtont];
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    
    //设置默认搜索时间(本月)
    NSString *time = [GEDateFromatter formmatTimeDate:[NSDate date] format:@"yyyy-MM"];
    self.searchStartTime = [NSString stringWithFormat:@"%@-01",time];
    self.searchEndTime = [GEDateFromatter formmatTimeDate:[NSDate date]];
    
    NSString *startTime = [self.searchStartTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSString *endTime = [self.searchEndTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    self.searchTimeLabel.text = [NSString stringWithFormat:@"检索时间 %@ - %@",startTime, endTime];
    
    self.tableView.SKSTableViewDelegate = self;
    self.tableView.shouldExpandOnlyOneCell = YES;
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    [self.segmentedView addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self setupRefresh];
}

- (void)dealloc
{
    NSLog(@"MJTableViewController--dealloc---");
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger index = Seg.selectedSegmentIndex;
    self.segmentActionState = index;
    
    [self.resultData removeAllObjects];
    [self.tableView refreshData];
    [self.tableView headerBeginRefreshing];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:20];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //合同状态：0全部，1待授权，2已授权，3已终止
    NSString *RWDZTString = nil;
    if (self.segmentActionState == 0) {
        RWDZTString = [NSString stringWithFormat:@"材料"];
    } else if (self.segmentActionState == 1) {
        RWDZTString = [NSString stringWithFormat:@"供应商"];
    }
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"YCL_JLTJ_LIST20160129"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    //设置站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    [content setStationID:[model.stationId integerValue]];
    
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"分类" value:RWDZTString];
    [content addParameterKey:@"开始日期" value:self.searchStartTime];
    [content addParameterKey:@"截止日期" value:self.searchEndTime];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        
        //添加数据，刷新页面
        if(isReresh) [self.resultData removeAllObjects];
        if(result.resultArray && result.resultArray.count>1){
            NSMutableArray *valueArray = [self dataQueryHandle:result.resultArray];
            [self.resultData addObjectsFromArray:valueArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView refreshData];
            
            if(isReresh && !(valueArray && valueArray.count > 0))
                [self.tableView setTableViewNotDataDrawText:@"暂无原材数据" isShow:YES];
            
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无原材数据" isShow:YES];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
}

- (NSMutableArray*)dataQueryHandle:(NSArray*)array
{
    //数据查询
    NSMutableArray *compArray = [NSMutableArray arrayWithArray:[array firstObject]];
    NSMutableArray *htArray = [NSMutableArray arrayWithArray:[array lastObject]];
    
    for(int i=0;i<compArray.count;i++){
        NSDictionary *dic = [compArray objectAtIndex:i];
        
        NSArray *filteredArray = nil;
        if (self.segmentActionState == 0) { //材料
            NSInteger clientID = [dic objectFormatIntegerForKey:@"CLID"];
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"CLID==%ld", clientID];
            filteredArray = [htArray filteredArrayUsingPredicate:predicate];
            
        } else if (self.segmentActionState == 1) { //供应商
            NSInteger clientID = [dic objectFormatIntegerForKey:@"GYSID"];
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"GYSID==%ld", clientID];
            filteredArray = [htArray filteredArrayUsingPredicate:predicate];
        }
        
        NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        [mutableDic setValue:filteredArray forKey:@"itemValue"];
        [compArray setObject:mutableDic atIndexedSubscript:i];
    }
    
    return compArray;
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MCChargeInViewCell";
    MCChargeInViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell){
        cell = [[MCChargeInViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    [cell setIsShowAccessory:YES];
    NSDictionary *itemData = [self.resultData objectAtIndex:indexPath.row];
    
    if (self.segmentActionState == 0) { //材料分类
        cell.nameLabel.text = [itemData objectFormatStringForKey:@"材料名称" defaults:@"未知"];
        cell.yczzlLabel.text = [itemData objectFormatFloatStringForKey:@"打印净重" retain:1 except:10000 exceptFormat:@"%@万吨" format:@"%@吨"];
        
    } else { //供应商分类
        cell.nameLabel.text = [itemData objectFormatStringForKey:@"供应商" defaults:@"未知"];
        cell.yczzlLabel.text = [itemData objectFormatFloatStringForKey:@"打印净重" retain:1 except:10000 exceptFormat:@"%@万吨" format:@"%@吨"];
    }
    
    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MCChargeInRowViewCell";
    MCChargeInRowViewCell *cell = [[MCChargeInRowViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell setChartViewAnimated];
    [cell setNavigationController:self.navigationController indexPath:indexPath];
    [cell setSearchStartTime:_searchStartTime endTime:_searchEndTime];
    
    //无数据绘制提示
    NSDictionary *dic = [self.resultData objectAtIndex:indexPath.row];
    NSArray *rowValueArray = [dic objectFormatForKey:@"itemValue"];
    if (rowValueArray.count <= 0) {
        [cell drawNotDataNotReloadTableView:tableView rect:CGRectMake(0, 60, SuperWidth, 180)];
        return cell;
    }
    
    if (self.segmentActionState == 0) { //材料分类
        [cell setSupplierData:rowValueArray];
    } else { //供应商分类
        [cell setMaterialData:rowValueArray];
    }
    
    return cell;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
//    return 300;
//    
    NSDictionary *dic = [self.resultData objectAtIndex:indexPath.row];
    NSArray *rowValueArray = [dic objectFormatForKey:@"itemValue"];
    if (rowValueArray.count <= 0) return 240;
    else return 300;
}

#pragma mark -
#pragma mark SKSTableViewDelegate

- (void)tableView:(SKSTableView *)tableView accessoryDidExpandIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *indexRowPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
    MCChargeInRowViewCell *cell = [tableView cellForRowAtIndexPath:indexRowPath];
    if(cell && [cell isKindOfClass:[MCChargeInRowViewCell class]])[cell setChartViewAnimated];
}

- (void)tableView:(SKSTableView *)tableView accessoryNotExpandIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Section: %ld, Row:%ld, Subrow:%ld", (long)indexPath.section, indexPath.row, (long)indexPath.subRow);
}

- (void)tableView:(SKSTableView *)tableView didSelectSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Section: %ld, Row:%ld, Subrow:%ld", indexPath.section, (long)indexPath.row, (long)indexPath.subRow);
//    NSDictionary *dic = [self.resultData objectAtIndex:indexPath.row];
//    NSArray *rowValueArray = [dic objectFormatForKey:@"itemValue"];
//    NSDictionary *itemData = [rowValueArray objectAtIndex:indexPath.subRow-1];
    
}

#pragma mark -
#pragma mark IBAction

- (void)searchChargeInSelector:(id)sender
{
    MCSearchChargeInViewController *view = [[MCSearchChargeInViewController alloc] init];
    view.backResultDelagate = self;
    AbstractNavigationController *navigation = [[AbstractNavigationController alloc] initWithRootViewController:view];
    [self.navigationController presentViewController:navigation animated:YES completion:nil];
}

#pragma mark - Other Method

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    if (!backValue) return;
    
    NSArray *array = backValue;
    self.searchStartTime = array[0];
    self.searchEndTime = array[1];
    
    NSString *startTime = [self.searchStartTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSString *endTime = [self.searchEndTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    self.searchTimeLabel.text = [NSString stringWithFormat:@"检索时间 %@ - %@",startTime, endTime];
    
    [self.resultData removeAllObjects];
    [self.tableView refreshData];
    [self.tableView headerBeginRefreshing];
}

@end
